function prependBaseUrl(url) {
  return url.startsWith("http") ? url : `${process.env.BASE_URL}${url}`;
}

function appendParamsToUrl(url, params) {
  const queryString = new URLSearchParams(params).toString();
  return queryString
    ? `${url}${url.includes("?") ? "&" : "?"}${queryString}`
    : url;
}

function request(url, options = {}) {
  const { params = {}, ...restOptions } = options;
  const finalUrl = appendParamsToUrl(prependBaseUrl(url), params);
  return new Promise((resolve, reject) => {
    uni.request({
      url: finalUrl,
      method: restOptions.method || "GET",
      data: restOptions.body || {},
      header: restOptions.headers || {},
      success: (res) => resolve(res.data),
      fail: (error) => {
        console.error("Request failed:", error);
        reject(error);
      },
    });
  });
}

function upload(url, file, options = {}) {
  const { params = {}, ...restOptions } = options;
  const finalUrl = appendParamsToUrl(prependBaseUrl(url), params);
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: finalUrl,
      filePath: file,
      name: "file",
      header: restOptions.headers || {},
      success: (res) => resolve(JSON.parse(res.data)),
      fail: (error) => {
        console.error("Upload failed:", error);
        reject(error);
      },
    });
  });
}

// Export the methods if needed
export { request, upload };
